import json
import re
import time
import urllib
from selenium import webdriver
import requests
cookie=""#账号信息
turn=""
requestId=""
response=""
username=input("请输入你的学号：")
password=input("请输入你的密码：")
lessonAssoc=int(input("请输入你要学的课程号："))=#课程信息，课程号

#获取cookie
def get_cookie():
    EDGE = {
        "browserName": "MicrosoftEdge",
        "version": "99.0.1150.39",
        "platform": "WINDOWS",
        "ms:edgeOptions": {
            'extensions': [],
            'args': [
                '--headless',
                '--disable-gpu'
            ]}
    }  #设置为无头模式
    driver = webdriver.Edge(executable_path="C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe", capabilities=EDGE)  # Edge浏览器"C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe"
    driver.get('https://cas.paas.jmu.edu.cn/cas/login?service=http%3A%2F%2Fjwxt.jmu.edu.cn%2Fstudent%2Fsso%2Flogin')
    print(driver.title)
    # username=driver.find_element_by_xpath('//*[@id="username"]')
    # username.click()#点击事件
    # 找到用户名然后输入账号
    driver.find_element_by_xpath('//*[@id="username"]').send_keys(username)
    # 找到密码框然后输入密码
    driver.find_element_by_xpath('//*[@id="password"]').send_keys(password)
    # 找到登陆按钮并点击登陆
    driver.find_element_by_xpath('//*[@id="fm1"]/div[4]/div/input[7]').click()
    time.sleep(3)
    print(driver.title)
    # 找到选课按钮并单机,进入选课系统页面
    driver.find_element_by_xpath('//*[@id="commonServices"]/div/div[2]/div[1]/div[5]/div/div[1]').click()
    # 关闭子窗口
    driver.close()
    # 切换窗口,选择-1及最后一个窗口
    handles = driver.window_handles  # 再次获取窗口句柄handles
    # print('新窗口句柄为：{0}'.format(handles))
    # 新老句柄列表可以看出，新出现的句柄在列表里面排在后面
    driver.switch_to.window(handles[-1])  # 执行切换窗口操作
    print(driver.title)

    SESSION = driver.get_cookie("SESSION")
    # print(SESSION['value'])
    SESSION = SESSION['value']
    __pstsid__ = driver.get_cookie("__pstsid__")
    # print(__pstsid__['value'])
    __pstsid__ = __pstsid__['value']
    cookie = f'SESSION={SESSION}; __pstsid__={__pstsid__}'
    print(cookie)
    return cookie








#获取turnId
def getturn(turn):
    url=" http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/open-turns"
    headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.39",
        "Cookie": cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection":"keep-alive",
        "Content-Length": "42",
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Origin":"http://jwxt.jmu.edu.cn",
        "Referer":"http://jwxt.jmu.edu.cn/student/for-std/course-select/single-student/turns"
    }
    date={
    "bizTypeId": 2,
    "studentId": 4759,
    "departmentId": 17
          }
    response=requests.post(url=url, headers=headers, data=date,verify=False)
    all_course=response.json()
    print("可选择的板块----从0开始按顺序排序如下")
    number=0;
    for i in all_course:
        print(number,i)
        number+=1

    youchoice=int(input("请输入你选择的板块（从0开始）"))
    turn=all_course[youchoice]['id']
    print(turn)
    return turn



#add-predicate(包含课程信息）
def add_predicate(requestId):
    print("正在add-predicate...(其中包含课程信息）")
    url=" http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/add-predicate"

    headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.39",
        "Cookie": cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection":"keep-alive",
        "Content-Length": "159",
        "Content-Type":"application/json",
        "Origin":"http://jwxt.jmu.edu.cn"
        #"Referer":f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date={"studentAssoc":4759,
          "courseSelectTurnAssoc":1361,
          "requestMiddleDtos":[
              {
                  "lessonAssoc":lessonAssoc,
                  "virtualCost":0,
                  "scheduleGroupAssoc":None}
          ],
          "coursePackAssoc":None
          }
    date= json.dumps(date)
    print(type(date))
    response=requests.post(url=url, headers=headers, data=date,verify=False)
    #print(type(response))
    print(response.content)
    #print(type(response.content))
    #print(response.status_code)
    requestId=(response.content)
    return requestId


#predicate-response
def predicate_response(response):
    print("正在predicate-response...")
    url="http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/predicate-response"

    headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30",
        "Cookie":cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection":"keep-alive",
        "Content-Length": "61",
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Origin":"http://jwxt.jmu.edu.cn",
        "Referer":f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date={
        "studentId": "4759",
        "requestId": requestId
    }

    response=requests.post(url=url, headers=headers, data=date,verify=False)
    print(response.text)
    return response



#add-request
def add_request(requestId):
    print("正在add-request...（包含课程信息）")
    url="http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/add-request"

    headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30",
        "Cookie":cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection":"keep-alive",
        "Content-Length": "136",
        "Content-Type":"application/json",
        "Origin":"http://jwxt.jmu.edu.cn",
        "Referer":f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date={"studentAssoc":4759,"courseSelectTurnAssoc":1361,"requestMiddleDtos":[{"lessonAssoc":lessonAssoc,"virtualCost":0,"scheduleGroupAssoc":None}]}
    date= json.dumps(date)
    response=requests.post(url=url, headers=headers, data=date,verify=False)
    print(response.content)
    requestId=response.content
    return requestId


#add-drop-response
def add_drop_response():
    print("正在add-drop-response...")
    url="http://jwxt.jmu.edu.cn/student/ws/for-std/course-select/add-drop-response"

    headers={
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30",
        "Cookie":cookie,
        "Host": "jwxt.jmu.edu.cn",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection":"keep-alive",
        "Content-Length": "136",
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Origin":"http://jwxt.jmu.edu.cn",
        "Referer":f"http://jwxt.jmu.edu.cn/student/for-std/course-select/4759/turn/{turn}/select"
    }
    date={
    "studentId": 4759,
    "requestId": requestId
    }

    response=requests.post(url=url, headers=headers, data=date,verify=False)
    print(response.text)
    result=response.text

    try:
        tishi = re.compile(r'.*?,"text":"(?P<tishi>.*?)"}', re.S)
        tishi=re.search(tishi,result).group("tishi")
        print("选课结果提示:"+tishi)
    except Exception as cuowu:
        print("无提示！",cuowu)
    try:
        jieguo = re.compile(r'.*?,"success":(?P<issuccess>.*?),"', re.S)
        issuccess=re.search(jieguo,result).group("issuccess")
        print("选课结果："+issuccess)
    except Exception as cuowu:
        print("无结果！",cuowu)
    return

if __name__ == '__main__':
    # 获取turnId
    result="false"
    cookie=get_cookie()
    # turn=getturn(turn)
    # add-predicate(包含课程信息）
    requestId=add_predicate(requestId)
    # predicate-response
    response=predicate_response(response)
    # add-request
    requestId=add_request(requestId)
    # add-drop-response
    add_drop_response()

